<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible"
      :before-close="handleClose"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="150px"
      >
        <el-form-item label="彩蛋名称" prop="chapterName">
          <el-input v-model="dataForm.chapterName" placeholder="彩蛋名称"></el-input>
        </el-form-item>
        <el-form-item label="配置播放量" prop="chapterVisit">
          <el-input v-model.number="dataForm.chapterVisit" placeholder="非实际播放量" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="彩蛋音频" prop="audioUrl">
          <div>
            <audio
              controls="controls"
              v-if="dataForm.audioUrl!=''"
              id="myaudio"
              :src="dataForm.audioUrl"
              type="audio/mp3"
            ></audio>
            <span style="color:#00f;cursor: pointer; " v-if="dataForm.audioUrl!=''">{{dataForm.audioName}}</span>
          </div>
          <el-upload
            ref="replaceUploader"
            :file-list="replaceList"
            class="avatar-uploader"
            :action="url"
            :multiple="false"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :beforeUpload="beforeAvatarUpload"
            :on-remove="removefile"
            :on-change="handleChange"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="彩蛋内容" prop="content" class="content">
          <template>
            <script :id="cueId" class="ueditor-box" type="text/plain">
  {{dataForm.content}}
            </script>
          </template>
        </el-form-item>
        <el-form-item label="上架时间" prop='isAlive'>
          <el-radio v-model="dataForm.isAlive" :label="1" :disabled="isAlive === 1">立即上架</el-radio>
          <el-radio v-model="dataForm.isAlive" :label="2" :disabled="isAlive === 1">定时上架</el-radio>
          <el-date-picker
            popper-class = 'dingTime'
            v-if="dataForm.isAlive === 2"
            v-model="dataForm.publishTime"
            type="datetime"
            placeholder="选择推送时间"
            style="margin-left: 20px;"
            @change="changeTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            :disabled="isAlive === 1"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="preview()">预览</el-button>
        <el-button @click="down()">取消</el-button>
        <el-button type="primary" @click="getContent()">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :visible.sync="qrcode" width="30%">
      <div class="qrcode">
        <img :src="qrimg">
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss">
.content .ueditor-box {
  height: 150px!important;
}
.qrcode {
  width: 200px;
  height: 200px;
  margin: 0 auto;
}
.qrcode img {
  width: 100%;
  height: 100%;
}
.content {
  height: 520px !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<script>
import ueditor from "ueditor";

export default {
  data() {
    return {
      visible: false,
      audios: false,
      objaudio: false,
      listens: true,
      qrcode: false,
      dataForm: {
        id: 0,
        isAlive: 1,
        bookId: "",
        chapterNo: "",
        chapterName: "",
        audioUrl: "",
        audioTime: "",
        audioName: "",
        content: "",
        wordNumber: "",
        chapterVisit: "",
        chapterVisitCount: "",
        publishTime: '',
        videoCoverImageUrl: "",
        videoStatus: "",
        videoUrl: "",
        videoTime: "",
        videoName: ""
      },
      isAlive: '',
      dataRule: {
        chapterName: [
          { required: true, message: "彩蛋名称不能为空", trigger: "blur" },
          { max: 18, message: "最长18个字符", trigger: "blur" }
        ],
        chapterVisit: [
          { required: true, message: "配置播放量不能为空", trigger: "blur" },
          { type: "number", message: "请输入数字", trigger: "blur" }
        ]
      },
      url: "",
      ue: null,
      cueId: `J_ueditorBox_${new Date().getTime()}`,
      ueContent: "",
      replaceList: [],
      qrimg: "", //二维码
      getQr: "",
     // videourl: "", //视频url
      imageUrl: "", //图片路径
      uploadUrl: "" //上传图地址
    };
  },
  mounted() {
    // 上传音频
    this.url = this.$http.adornUrl(
      `/colorEgg/eggChapter/upload/audio?token=${this.$cookie.get("token")}`
    );
    // 上传视频
    // this.videourl = this.$http.adornUrl(
    //   `/colorEgg/eggChapter/upload/video?token=${this.$cookie.get("token")}`
    // );
    // 上传视频封面
    // this.uploadUrl = this.$http.adornUrl(
    //   `/colorEgg/eggChapter/upload/videoCover?token=${this.$cookie.get(
    //     "token"
    //   )}`
    // );
  },
  methods: {
    // 关闭窗口音频就关闭
    handleClose() {
      let that = this;
      this.visible = false;
      var myAuto = document.getElementById("myaudio");
      if (myAuto) {
        myAuto.pause();
        myAuto.load();
        that.ue.execCommand("cleardoc");
      } else {
        that.ue.execCommand("cleardoc");
      }
    },
    // 预览
    preview() {
      this.ue.ready(() => {
        this.ueContent = this.ue.getContent();
      });
      this.getQr = this.ueContent.replace(
        /<img/g,
        "<img style='width:100%;height:auto'"
      );
      let audio = ''
      if(this.dataForm.audioUrl) {
        audio = `<div><audio controls="controls" style="width: 100%;" src="${this.dataForm.audioUrl}" /></div>`
      }
      this.$http({
        url: this.$http.adornUrl("/colorEgg/eggChapter/getQr"),
        method: "post",
        data: this.$http.adornData({
          content: audio+this.getQr
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.qrcode = true;
          this.qrimg = data.qrUrl;
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    // 取消按钮音频就关闭并且富文本清空
    down() {
      let that = this;
      this.visible = false;
      var myAuto = document.getElementById("myaudio");
      if (myAuto) {
        myAuto.pause();
        myAuto.load();
        that.ue.execCommand("cleardoc");
      } else {
        that.ue.execCommand("cleardoc");
      }
    },
    // 移除音频
    removefile() {
      this.dataForm.audioUrl = ""
    },
    init(data) {
      setTimeout(() => {
        this.ue = ueditor.getEditor(this.cueId, {
          // serverUrl: '', // 服务器统一请求接口路径
          zIndex: 3000
        });
      }, 100);
      this.dataForm.id = data.id || 0;
      if (data.bookId) {
        this.dataForm.bookId = data.bookId;
      }
      this.visible = true;
      this.$nextTick(() => {
        this.isAlive = ''
        this.$refs["dataForm"].resetFields();
        this.$refs.replaceUploader.clearFiles();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/colorEgg/eggChapter/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.bookId = data.bookChapter.bookId;
              this.dataForm.chapterName = data.bookChapter.chapterName;
              this.dataForm.chapterVisit = data.bookChapter.chapterVisit;
              this.dataForm.audioName = data.bookChapter.audioName;
              this.dataForm.audioTime = data.bookChapter.audioTime;
              this.dataForm.audioUrl = data.bookChapter.audioUrl;
              this.dataForm.chapterVisit = data.bookChapter.chapterVisit;
              this.dataForm.isAlive = data.bookChapter.isAlive
              this.dataForm.publishTime = data.bookChapter.publishTime
              this.isAlive = data.bookChapter.isAlive
              this.dataForm.content = data.bookChapter.content;
              this.ue.ready(() => {
                this.ue.setContent(this.dataForm.content);
              });
            }
          });
        }
      });
    },
    handleAvatarSuccess(response, file, fileList) {
      this.replaceList = fileList;
      this.successNum++;
      if (response && response.code === 0) {
        if (this.num === this.successNum) {
          this.$confirm("操作成功, 是否继续操作?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).catch(() => {
            this.visible = false;
          });
        }
        this.dataForm.audioUrl = response.url;
        this.dataForm.audioName = file.name;
        this.audios = true;
        this.objaudio = false;
        this.listens = false;
      } else {
        this.$message.error(response.msg);
      }
    },
    // 上传音频
    beforeAvatarUpload(file) {
      this.objaudio = false;
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);

      const extension = testmsg === "mp3";
      if (!extension) {
        this.$message({
          message: "上传文件只能是mp3格式！",
          type: "error"
        });
      }
      return extension;
    },
    // 改变上传的时候取最后一个，实现替换上传
    handleChange(files, fileList) {
      // 获取最后一次得到的文件
      const aa = fileList[fileList.length - 1];
      // 覆盖上一次的文件
      this.replaceList = [];
      this.replaceList.push(aa);
    },
    // //上传视频
    // beforeUploadVideo(file) {
    //   const isLt10M = file.size / 1024 / 1024 < 10;
    //   if (
    //     [
    //       "video/mp4",
    //       "video/ogg",
    //       "video/flv",
    //       "video/avi",
    //       "video/wmv",
    //       "video/rmvb"
    //     ].indexOf(file.type) == -1
    //   ) {
    //     this.$message.error("请上传正确的视频格式");
    //     return false;
    //   }
    //   if (!isLt10M) {
    //     this.$message.error("上传视频大小不能超过10MB哦!");
    //     return false;
    //   }
    // },
    // //视频上传成功
    // handleVideoSuccess(response, file, fileList) {
    //   this.replaceList = fileList;
    //   this.successNum++;
    //   if (response && response.code === 0) {
    //     if (this.num === this.successNum) {
    //       this.$confirm("操作成功, 是否继续操作?", "提示", {
    //         confirmButtonText: "确定",
    //         cancelButtonText: "取消",
    //         type: "warning"
    //       }).catch(() => {
    //         this.visible = false;
    //       });
    //     }
    //     this.dataForm.videoUrl = response.url;
    //     this.dataForm.videoName = response.name;

    //     // this.dataForm.sourceInfo.video_name = file.name;
    //   } else {
    //     this.$message.error(response.msg);
    //   }
    // },
    // // 上传视频封面
    // handleimgSuccess(res, file) {
    //   this.dataForm.videoCoverImageUrl = URL.createObjectURL(file.raw);
    // },
    // beforeimgUpload(file) {
    //   const isJPG = file.type === "image/png";
    //   if (!isJPG) {
    //     this.$message.error("上传头像图片只能是 png 格式!");
    //   }
    //   return isJPG;
    // },
    // 表单提交
    changeTime () {
      if (new Date(this.dataForm.pushTime).getTime() < new Date().getTime()) {
        this.dataForm.pushTime = ''
        this.$message.error('所选时间要大于当前时间')
      }
    },
    getContent(res, file) {
      // 获取音频时长
      // 这里加了下判断，是在修改的时候修改其他字段不改这个音频也不会报错
      if (document.getElementById("myaudio")) {
           this.dataForm.audioTime = document.getElementById("myaudio").duration * 1000;
      }
      let that = this;
      this.ue.ready(() => {
        this.ueContent = this.ue.getContent();
      });
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/colorEgg/eggChapter/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              bookId: this.dataForm.bookId,
              chapterName: this.dataForm.chapterName,
              audioTime: this.dataForm.audioTime,
              audioName: this.dataForm.audioName,
              audioUrl: this.dataForm.audioUrl,
              isAlive: this.dataForm.isAlive,
              publishTime: this.dataForm.publishTime,
              // videoStatus: this.dataForm.videoStatus,
              // videoUrl: this.dataForm.videoUrl,
              // videoName: this.dataForm.videoName,
              // videoTime: this.dataForm.videoTime,
              content: this.ueContent,
              chapterVisit: this.dataForm.chapterVisit,
              id: this.dataForm.id || undefined
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration:1200,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList", this.dataForm.bookId);
                }
              });
              that.ue.execCommand("cleardoc");
              this.audios = false;
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
